<?php

namespace Frieza\Modules\PublishSetting\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\PublishSetting\PublishSetting as mPublishSetting;
use Doraemon\pockets\constInterface\DecorationDiary\DecorationStage;

class DiaryStageController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $search = [];
        $search['publish_type'] = mPublishSetting::PUBLISH_TYPE_DIARY;
        $search['sub_type_id[!]'] = 0;

        $list = mPublishSetting::findPageList($search, $page, $pageSize);
        if (!empty($list) && !empty($list['list'])) {
            foreach ($list['list'] as &$value) {
                $value['stage_name'] = DecorationStage::SUB_STAGE_MAP[$value['sub_type_id']] ?? '';
            }
        }

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();

                $grid->column('id', 'ID');
                $grid->column('stage_name', '阶段名称');
                $grid->column('content_desc', '发布器引导文案');
                $grid->column('suggestion', '正文小标题');

                $grid->column('edittime', '修改时间')->display(function () {
                    if ($this->edittime) {
                        return date("Y-m-d H:i:s", $this->edittime);
                    } else {
                        return '--';
                    }
                });

                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->oper_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->oper_id)->name;
                    }
                });
            });

        return $content
            ->header('装修日记阶段')
            ->description(' ')
            ->breadcrumb(
                [
                    'text' => '装修日记阶段发布器列表',
                    'url' => '/publishSetting/diaryStage/index',
                ],
            )
            ->row($gridList);
    }

    public function del($id)
    {
        $data = mPublishSetting::getById($id);
        if ($data) {
            $data['biz_status'] = mPublishSetting::STATUS_DELETE;
            $data['oper_id'] = Admin::user()->id;
            $data['edittime'] = time();

            $rs = mPublishSetting::updateById($id, $data);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function edit(Content $content, $id = 0)
    {
        if ($id > 0) {
            $title = '编辑装修日记阶段发布器';
        } else {
            $title = '添加装修日记阶段发布器';
        }
        $tab = new Tab();
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('装修日记阶段')
            ->breadcrumb(
                [
                    'text' => '装修日记阶段列表',
                    'url' => '/publishSetting/diaryStage/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);


    }


    public function editAction($id = 0)
    {
        $data = [];
        if ($id != 0) {
            //修改
            $data = mPublishSetting::getById($id);
            $form = new Form($data);
        } else {
            //添加
            $form = new Form($data);
        }
        $form->hidden('id');
        $mapList = DecorationStage::RELATIONSHIP;
        $allStage = DecorationStage::STAGE_MAP;
        $stage = 0;
        $subTypeId = $data['sub_type_id'] ?? 0;
        $allSubStage = [];
        if (!empty($subTypeId)) {
            foreach ($mapList as $stageId => $subStageIdList) {
                if (in_array($subTypeId, $subStageIdList)) {
                    $stage = $stageId;
                    foreach ($subStageIdList as $k) {
                        $allSubStage[$k] = DecorationStage::SUB_STAGE_MAP[$k] ?? '';
                    }
                    break;
                }
            }
        }
        $form->select('stage', '阶段')->options($allStage)->default($stage)
            ->load('sub_stage', route('diaryStage.stage'))->required();
        $form->select('sub_stage', '子阶段')->options($allSubStage)->default($subTypeId)->required();
        $form->textarea('content_desc', '正文默认文案')
            ->default($data['content_desc'] ?? '');
        $form->text('suggestion', '键盘上方正文小标题')
            ->default($data['suggestion'] ?? '')
            ->placeholder('以英文逗号分隔，最多五条');
        $form->action('/admin/publishSetting/diaryStage/index/save');

        return $form->render();
    }

    public function save(Request $request, Content $content)
    {
        $request = $request->all();
        $id = $request['id'] ?? '';
        $contentDesc = $request['content_desc'] ?? '';
        $suggestion = $request['suggestion'] ?? '';
        $suggestion = trim($suggestion, ',');
        $subTypeId = $request['sub_stage'] ?? '';
        if (empty($subTypeId)) {
            return back()->withInput()->with(['error' => new MessageBag([
                'title' => '装修阶段不能为空',
            ])]);
        }
        if (empty($contentDesc) && empty($suggestion)) {
            return back()->withInput()->with(['error' => new MessageBag([
                'title' => '正文默认文案和小建议不能同时为空',
            ])]);
        }
        if (count(explode(',', $suggestion)) > 5) {
            return back()->withInput()->with(['error' => new MessageBag([
                'title' => '小建议最多支持5条',
            ])]);
        }

        $time = time();
        $data['content_desc'] = $contentDesc;
        $data['suggestion'] = $suggestion;
        $data['sub_type_id'] = $subTypeId;
        $data['oper_id'] = Admin::user()->id;
        $data['edittime'] = $time;

        if ($id) {
            $rs = mPublishSetting::updateById($id, $data);
        } else {
            $data['publish_type'] = mPublishSetting::PUBLISH_TYPE_DIARY;
            $data['addtime'] = $time;
            $rs = mPublishSetting::add($data);
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/publishSetting/diaryStage/index')->with(compact('success'));
        } else {
            return back()->withInput()->with(['error' => new MessageBag([
                'title' => '提交失败',
            ])]);
        }


    }


    public function stage(Request $request)
    {
        $pid = $request->input('q', 0);
        $list = DecorationStage::RELATIONSHIP[$pid] ?? [];
        if (empty($list)) {
            return response()->json([]);
        }
        $format = array_map(function ($k) {
            return [
                'id' => $k,
                'text' => DecorationStage::SUB_STAGE_MAP[$k] ?? '',
            ];
        }, array_values($list));
        return response()->json($format);
    }
}